from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from config import get_config
# 配置文件
settings = get_config()
# 数据库连接引擎
engine = create_engine(
    'mysql+pymysql://%s:%s@%s:%s/%s?charset=utf8mb4' % (settings.DB_USER, settings.DB_PASSWORD, settings.DB_HOST, settings.DB_PORT, settings.DB_NAME),
    echo=True
) 
# 数据库连接对象
SessionLocal = sessionmaker(bind=engine)
# 基类
Base = declarative_base()
# 同步数据库
def create_tables():
    Base.metadata.create_all(bind=engine)
# 获取数据库对象
def get_db():
    current_db = SessionLocal()
    try:
        yield current_db
    finally:
        current_db.close()